/*
 * MyLogger.java - MyLogger 记录日志、错误
 * @author Zhang Nan
 * @since [28/02/2017]
 *
 */

package io.tim.webserver.simple02.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MyLogger {

	private final Map<Integer, String> errorMap = new HashMap<Integer, String>();

	// 致命错误
	private final int FATAL_ERROR = 1;

	// 错误请求
	private final int BADREQUEST_ERROR = 2;

	// 未知错误
	private final int UNHANDLED_ERROR = 3;

	// 非关键错误
	private final int ERROR = 4;

	public MyLogger() {
		errorMap.put(this.FATAL_ERROR, "FATAL ERROR");
		errorMap.put(this.BADREQUEST_ERROR, "REQUESTE ERROR");
		errorMap.put(this.UNHANDLED_ERROR, "UNHANDLED ERROR");
		errorMap.put(this.ERROR, "ERROR");
	}

	public void LogEvent(String LogFilePath, String Msg, int ErrorNumber) throws IOException {

		File logFile = new File(LogFilePath);
		BufferedWriter Bw = null;
		Date logDate = new Date();

		String today = DateFormat.getInstance().format(logDate);

		if (!logFile.exists()) {
			FileOutputStream fp = new FileOutputStream(LogFilePath);
		}

		if (logFile.canWrite()) {
			// FileWriter append=true
			FileWriter fw = new FileWriter(LogFilePath, true);

			Bw = new BufferedWriter(fw);

		}
		// 根据错误代码 ErrorNumber 指定日志的信息

		Bw.write("[" + today + "] [" + errorMap.get(ErrorNumber) + "]  " + Msg + "\r\n");

		Bw.close(); // closing File MyLogger

	}
}// End class MyLogger